<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分配权限</title>
    <script src="/layui/layui.js"></script>
    <link rel="stylesheet" href="/layui/css/layui.css">
    <script src="/js/jquery.js"></script>
    <script src="/js/myAjax.js"></script>
</head>
<body>
<div type="hidden" id="roleId"></div>
<div id="test1" style="margin-left: 50px;margin-top: 50px"></div>
<!--<div><input type="button" value="确认" onclick="confrim()"></div>-->
<script>
    layui.use('transfer', function () {
        var transfer = layui.transfer;

        function findPermission() {
            let data = myAjax('/permission/findAll', 'post', {});
            let data1 = [];
            for (let i = 0; i < data.data.length; i++) {
                data1.push({"value": data.data[i].id, "title": data.data[i].name});
            }
            return data1;
        }

        function findByRoleId() {
            let id = sessionStorage.getItem("roleId");
            let data2 = [];
            let result = myAjax('/role/findByRoleId', 'post', {id: id});
            console.log(result);
            for (let i = 0; i < result.data.length; i++) {
                data2.push(result.data[i].permissionId);
            }
            return data2;
        }

        let data = findPermission();
        let value = findByRoleId();
        //渲染
        transfer.render({
            elem: '#test1'  //绑定元素
            , showSearch: true
            , title: ['未拥有', '已拥有']
            , data: data
            , value: value
            , onchange: function (data, index) {
                //index=0就是添加的数据
                //index=1就是删除的数据
                let ids = [];
                let id = sessionStorage.getItem("roleId");
                for (let i = 0; i < data.length; i++) {
                    ids.push(data[i].value);
                }
                console.log(ids);
                if (index === 0) {
                    let result = myAjax('/role/addPermission', 'post', {id:id,ids:ids});
                    if (result.code === 200) {
                        layer.msg("添加成功");
                    } else {
                        layer.msg("添加失败")
                    }
                }
                if (index === 1) {
                    let result = myAjax('/role/deletePermission', 'get',{ids:ids,id:id});
                    if (result.code === 200) {
                        layer.msg("剔除成功");
                    } else {
                        layer.msg("剔除失败")
                    }
                }
            }
        });
    });
</script>
</body>
</html>